package Reflect_package1;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;

public class Reflect_demo2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        /*
            Class类中用于获取构造方法的方法：
                Constructor<?>[] getConstructors ()
                Constructor<?>[] getDeclaredConstructors ()
                Constructor<T> getConstructor (Class<?>...parameterTypes)
                Constructor<T> getDeclaredConstructor (Class<?>...parameterTypes)

            Constructor类中用于创建对象的方法：
                T newInstance (Object...initargs)
                setAccessible (boolean flag)
         */

        //1、获取class字节码文件对象
        Class<?> clazz = Class.forName("Reflect_package1.Student");

        //2、获取public构造方法
        Constructor<?>[] cons1 = clazz.getConstructors();

        for (Constructor<?> con : cons1) {
            System.out.println(con);
        }
        System.out.println("========================");

        //获取所有构造方法
        Constructor<?>[] cons2 = clazz.getDeclaredConstructors();
        for (Constructor<?> con : cons2) {
            System.out.println(con);
        }
        System.out.println("========================");

        //获取单个的构造方法
        Constructor<?> con1 = clazz.getDeclaredConstructor();
        System.out.println(con1);
        System.out.println("========================");

        Constructor<?> con2 = clazz.getDeclaredConstructor(String.class);
        System.out.println(con2);
        System.out.println("========================");

        Constructor<?> con3 = clazz.getDeclaredConstructor(String.class, int.class);
        System.out.println(con3);
        System.out.println("========================");


        //获取权限修饰符
        int modifiers = con3.getModifiers();
        System.out.println(modifiers);
        System.out.println("========================");

        //获取构造方法所有的参数
        Parameter[] parameters = con3.getParameters();
        for (Parameter parameter : parameters) {
            System.out.println(parameter);
        }
        System.out.println("========================");

        //创建对象
        Constructor<?> con4 = clazz.getDeclaredConstructor(int.class);
        con4.setAccessible(true);//暴力反射：表示临时取消权限校验
        Student stu = (Student) con4.newInstance( 23);

        System.out.println(stu);
    }
}
